# 还有一点错误, 有可能还python版本的不一致导致的, 也有解决的方法咱们没学会

# requests.get() 同步的代码 -> 异步操作aiohttp
import aiohttp
import asyncio

urls = [
        "https://www.umei.cc/d/file/20230914/41ba5a4992cfb63a5b3078657267d385.jpg",
        "https://www.umei.cc/d/file/20230914/d4870dca1d4bf8ba0ca84abc8298efdf.jpg",
        "https://www.umei.cc/d/file/20230914/e4e3c0afca3dba85af95132f2e0ec459.jpg"
    ]

async def aio_download(url):
    '''
    发送请求
    得到图片内容
    保存到文件

    s = aiohttp.ClientSession() <==> requests
    s.get()  <==>  requests.get()
    s.post()  <==>  requests.post()
    '''
    name = url.rsplit("/", 1)[1]  # 将url 从右边的'/'切一下, 取下标为 [1] 的内容
    async with aiohttp.ClientSession() as session:  # 相当于同步的 requests
        async with session.get(url) as resp:  # 相当于同步的 requests.get()
            # 写入文件
            # 学习aiofiles, 优化文件
            with open(f"img/{name}", mode="wb") as f:
                '''
                异步                    同步
                resp.content.read()    resp.content()
                resp.text()            resp.text
                resp.json()            resp.json()
                '''
                f.write(await resp.content.read())  # 读取内容是异步的, 需要await 挂起

    print(name, "OK")




async def main():
    tasks = []

    for url in urls:
        tasks.append(asyncio.create_task(aio_download(url)))

    await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main())


